import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  App as KonstaApp,
  Page,
} from 'konsta/react';
import { designSystem } from '../styles/colors';

export default function LoginPage() {
  const navigate = useNavigate();
  const [theme] = useState<'ios' | 'material'>('material');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleLogin = async () => {
    if (!username || !password) {
      setError('请输入用户名和密码');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await fetch('http://localhost:3000/auth/h5/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });

      const data = await response.json();

      if (data.code === 0 && data.data) {
        localStorage.setItem('token', data.data.token);
        localStorage.setItem('user', JSON.stringify(data.data.user));
        navigate('/home');
      } else {
        setError(data.message);
      }
    } catch (err) {
      console.error('登录错误:', err);
      setError('网络错误，请检查后端服务是否启动');
    } finally {
      setLoading(false);
    }
  };

  // 快速登录 - 使用测试账号
  const handleQuickLogin = async () => {
    setLoading(true);
    setError('');

    try {
      const response = await fetch('http://localhost:3000/auth/h5/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          username: 'h5admin', 
          password: '123456' 
        }),
      });

      const data = await response.json();

      if (data.code === 0 && data.data) {
        localStorage.setItem('token', data.data.token);
        localStorage.setItem('user', JSON.stringify(data.data.user));
        navigate('/home');
      } else {
        setError('快速登录失败：' + data.message);
      }
    } catch (err) {
      console.error('快速登录错误:', err);
      setError('网络错误，请检查后端服务是否启动');
    } finally {
      setLoading(false);
    }
  };

  return (
    <KonstaApp theme={theme}>
      <Page className="bg-gradient-to-br from-gray-50 to-blue-50">
        <div className="flex flex-col min-h-screen">
          {/* 顶部标题区域 */}
          <div className="pt-16 pb-8 px-6 text-center">
            <div className="inline-block mb-4">
              <div 
                className="w-16 h-16 rounded-2xl flex items-center justify-center shadow-lg"
                style={{ background: designSystem.gradients.primary }}
              >
                <span className="text-white text-3xl font-bold">¥</span>
              </div>
            </div>
            <h1 className="text-3xl font-bold text-gray-800 mb-2">
              通过账号密码验证身份
            </h1>
            <p className="text-gray-600 text-sm">欢迎登录金融平台</p>
          </div>

          {/* 主要内容卡片 */}
          <div className="flex-1 px-6">
            <div className="bg-white rounded-3xl shadow-2xl p-8 mb-6">
              {/* 登录表单 */}
              <div className="space-y-6 mb-6">
                {/* 用户名输入框 */}
                <div className="relative">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    用户名
                  </label>
                    <input
                      type="text"
                      value={username}
                      onChange={(e) => setUsername(e.target.value)}
                      placeholder="请输入用户名"
                      disabled={loading}
                      className="w-full px-4 py-3 border-2 rounded-xl focus:ring-0 outline-none transition-colors placeholder-gray-400 disabled:bg-gray-50"
                      style={{
                        borderColor: designSystem.bg.tertiary,
                        color: designSystem.text.primary,
                      }}
                      onFocus={(e) => (e.target.style.borderColor = designSystem.primary.main)}
                      onBlur={(e) => (e.target.style.borderColor = designSystem.bg.tertiary)}
                    />
                </div>

                {/* 密码输入框 */}
                <div className="relative">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    密码
                  </label>
                  <div className="relative">
                    <input
                      type={showPassword ? 'text' : 'password'}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="请输入密码"
                      disabled={loading}
                      className="w-full px-4 py-3 pr-12 border-2 rounded-xl focus:ring-0 outline-none transition-colors placeholder-gray-400 disabled:bg-gray-50"
                      style={{
                        borderColor: designSystem.bg.tertiary,
                        color: designSystem.text.primary,
                      }}
                      onFocus={(e) => (e.target.style.borderColor = designSystem.primary.main)}
                      onBlur={(e) => (e.target.style.borderColor = designSystem.bg.tertiary)}
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                      disabled={loading}
                    >
                      {showPassword ? (
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                        </svg>
                      ) : (
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                      )}
                    </button>
                  </div>
                </div>
              </div>

              {/* 错误提示 */}
              {error && (
                <div className="mb-6 p-3 bg-red-50 border border-red-200 rounded-xl">
                  <p className="text-red-600 text-sm text-center">{error}</p>
                </div>
              )}

              {/* 按钮组 */}
              <div className="flex gap-3 mb-4">
                <button
                  onClick={handleQuickLogin}
                  disabled={loading}
                  className="flex-1 py-3 px-4 bg-white border-2 rounded-xl font-medium hover:bg-gray-50 transition-colors disabled:opacity-50"
                  style={{
                    borderColor: designSystem.bg.tertiary,
                    color: designSystem.text.secondary,
                  }}
                >
                  {loading ? '登录中...' : '快速登录'}
                </button>
                <button
                  onClick={handleLogin}
                  disabled={loading}
                  className="flex-1 py-3 px-4 text-white rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                  style={{
                    backgroundColor: designSystem.primary.main,
                  }}
                >
                  {loading ? '登录中...' : '登录 →'}
                </button>
              </div>
            </div>


          </div>

          {/* 底部信息 */}
          <div className="pb-8 px-6 text-center">
            <p className="text-xs text-gray-400 mb-2">
              登录即表示同意
              <span style={{ color: designSystem.primary.main }}> 服务条款 </span>
              和
              <span style={{ color: designSystem.primary.main }}> 隐私政策</span>
            </p>
            <p className="text-xs text-gray-400">
              © 2025 金融平台 · 安全可信赖
            </p>
          </div>
        </div>
      </Page>
    </KonstaApp>
  );
}

